#![recursion_limit = "256"]
#[cfg(feature = "ssr")]
pub mod fallback;
pub mod adapters;
pub mod app;
pub mod components;
pub mod layout;
pub mod report;
pub mod utils;
pub mod auth;
pub mod kpi_import;
pub mod workflow;
pub mod context_menu;
pub mod shhr;
pub mod zhzjfp;

#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
    use log::Level;

    use crate::app::App;
    console_error_panic_hook::set_once();
    console_log::init_with_level(Level::Trace).expect("error initializing log");
    leptos::mount::hydrate_body(App);
}
#[cfg(feature = "ssr")]
pub async fn watching_config() {
    use notify::{Config, PollWatcher, RecursiveMode, Watcher};
    use shq_excel_report::{init_excel_import_config, reload_excel_rept_config};
    use shq_pas_backend::{init_app_config, init_menus_conf, reload_page_config};
    use shq_report::reload_rept_config;
    use std::{path::Path, time::Duration};
    use tokio::sync::mpsc;

    let conf_path = Path::new("./config_files").to_path_buf();
    let page_path = Path::new("./page_confs").to_path_buf();
    let rept_path = Path::new("./rept_confs").to_path_buf();
    let excel_rept_path = Path::new("./excel_rept_confs").to_path_buf();

    let config = Config::default()
        .with_compare_contents(true)
        .with_poll_interval(Duration::from_secs(5)); // Reduced interval for faster detection

    let (tx, mut rx) = mpsc::channel(100); // Use tokio's async channel

    let mut watcher = PollWatcher::new(
        move |res| {
            if let Err(err) = tx.blocking_send(res) {
                log::error!("发送事件到通道失败: {}", err);
            }
        },
        config,
    )
    .or_else(|err| Err(anyhow::anyhow!("创建watcher失败:{}", err)))
    .unwrap();

    watcher
        .watch(&conf_path, RecursiveMode::Recursive)
        .or_else(|err| {
            Err(anyhow::anyhow!(
                "监控文件夹{}失败:{}",
                &conf_path.display(),
                err
            ))
        })
        .unwrap();
    watcher
        .watch(&page_path, RecursiveMode::Recursive)
        .or_else(|err| {
            Err(anyhow::anyhow!(
                "监控文件夹{}失败:{}",
                &page_path.display(),
                err
            ))
        })
        .unwrap();
    watcher
        .watch(&rept_path, RecursiveMode::Recursive)
        .or_else(|err| {
            Err(anyhow::anyhow!(
                "监控文件夹{}失败:{}",
                &rept_path.display(),
                err
            ))
        })
        .unwrap();
    watcher
        .watch(&excel_rept_path, RecursiveMode::Recursive)
        .or_else(|err| {
            Err(anyhow::anyhow!(
                "监控文件夹{}失败:{}",
                &excel_rept_path.display(),
                err
            ))
        })
        .unwrap();
    log::info!("开始监控配置文件...");
    while let Some(event) = rx.recv().await {
        match event {
            Ok(event) => {
                for path in event.paths {
                    log::info!("监控到文件: {:?}", path);
                    if path.ends_with("app.yaml") {
                        if let Err(err) = init_app_config().await {
                            log::error!("重新加载配置文件app.yaml失败:{}", err);
                        }
                    } else if path.ends_with("menus.yaml") {
                        if let Err(err) = init_menus_conf() {
                            log::error!("重新加载配置文件menus.yaml失败:{}", err);
                        }
                    } else if path.ends_with("excel_import.yaml") {
                        if let Err(err) = init_excel_import_config().await {
                            log::error!("重新加载配置文件excel_import.yaml失败:{}", err);
                        }
                    } else if path
                        .to_str()
                        .map(|p| p.contains("/page_confs/") && p.ends_with(".yaml"))
                        .unwrap_or(false)
                    {
                        let file_name = path.file_name().unwrap().to_str().unwrap();
                        let page_name = &file_name[..file_name.len() - 5];
                        if let Err(err) = reload_page_config(&path).await {
                            log::error!("重新加载页面配置文件{}失败:{}", page_name, err);
                        }
                    } else if path
                        .to_str()
                        .map(|p| p.contains("/rept_confs/") && p.ends_with(".yaml"))
                        .unwrap_or(false)
                    {
                        let file_name = path.file_name().unwrap().to_str().unwrap();
                        let rept_name = &file_name[..file_name.len() - 5];
                        if let Err(err) = reload_rept_config(&path).await {
                            log::error!("重新加载报表配置文件{}失败:{}", rept_name, err);
                        }
                    } else if path
                        .to_str()
                        .map(|p| p.contains("/excel_rept_confs/") && p.ends_with(".yaml"))
                        .unwrap_or(false)
                    {
                        let file_name = path.file_name().unwrap().to_str().unwrap();
                        let rept_name = &file_name[..file_name.len() - 5];
                        if let Err(err) = reload_excel_rept_config(&path).await {
                            log::error!("重新加载excel报表配置文件{}失败:{}", rept_name, err);
                        }
                    }
                }
            }
            Err(e) => log::error!("watch error: {:?}", e),
        }
    }
}


